import { Component, Vue, Inject, Prop, Watch, Ref } from 'vue-property-decorator';
import { numeric, required, minLength, maxLength } from 'vuelidate/lib/validators';
import moment from 'moment';
import CommonTableService from '@/entities/modelConfig/common-table/common-table.service';
import { IAnnouncement, Announcement } from '@/shared/model/system/announcement.model';
import AnnouncementService from './announcement.service';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import { quillEditor } from 'vue-quill-editor';
import { UPLOAD_IMAGE_URL } from '@/constants';
import { ReceiverType } from '@/shared/model/enumerations/receiver-type.model';

import lowerFirst from 'lodash/lowerFirst';
import { generateDataForDesigner } from '@/utils/entity-form-utils';
import { idObjectArrayToIdArray, idsToIdObjectArray, getDataByFormField } from '@/utils/entity-utils';

const validations: any = {
  announcement: {
    id: {},
    titile: {},
    content: {},
    startTime: {},
    endTime: {},
    senderId: {},
    priority: {},
    category: {},
    receiverType: {},
    sendStatus: {},
    sendTime: {},
    cancelTime: {},
    businessType: {},
    businessId: {},
    openType: {},
    openPage: {},
    receiverIds: {},
    summary: {},
  },
};

@Component({
  validations,
  components: {
    'jhi-quill-editor': quillEditor,
  },
})
export default class AnnouncementUpdate extends Vue {
  // jhipster-pro-please-regenerate-this-file 如果您修改了此文件，并且不希望重新生成代码时被覆盖，请删除本行！！!

  @Inject('announcementService') private announcementService: () => AnnouncementService;
  @Inject('commonTableService') private commonTableService: () => CommonTableService;
  public announcement: IAnnouncement = new Announcement();
  public isSaving = false;
  public loading = false;
  @Ref('updateForm') readonly updateForm: any;
  public formJsonData = {
    list: [],
    config: {
      layout: 'horizontal',
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
      hideRequiredMark: false,
      customStyle: '',
    },
  };
  public relationshipsData: any = {};
  public dataFormContent = [];
  @Prop(Number) updateEntityId;
  @Prop(Boolean) showInModal;
  public dataContent = [];
  public announcementId = null;

  created(): void {
    // 判断是否从路由中获得实体id
    if (this.$route.params.announcementId) {
      this.announcementId = this.$route.params.announcementId;
    }
    this.initRelationships();
  }

  public mounted(): void {}

  public save(): void {
    this.isSaving = true;
    const that = this;
    this.updateForm
      .getData()
      .then(values => {
        Object.assign(that.announcement, values);
        if (that.announcement.id) {
          this.announcementService()
            .update(that.announcement)
            .then(param => {
              that.isSaving = false;
              const message = this.$t('jhipsterApp.announcement.updated', { param: param.id }).toString();
              this.$message.info(message);
              this.$router.go(-1);
            });
        } else {
          this.announcementService()
            .create(this.announcement)
            .then(param => {
              that.isSaving = false;
              const message = this.$t('jhipsterApp.announcement.created', { param: param.id }).toString();
              this.$message.success(message);
              this.$router.go(-1);
            });
        }
      })
      .catch(err => {
        this.$message.error('数据变更失败！');
        console.log(err);
      });
  }

  get receiveComponentProps() {
    const result: any = {
      show: false,
      props: {
        mode: 'multiple',
        valueField: 'id',
        labelField: '',
      },
      optionProps: {
        value: 'id',
        label: '',
      },
    };
    switch (this.announcement.receiverType) {
      case ReceiverType.ALL:
        result.show = false;
        result.selectListName = '';
        break;
      case ReceiverType.AUTHORITY:
        result.show = true;
        result.selectListName = 'jhi-authority-compact';
        result.props.labelField = 'name';
        result.optionProps.label = 'name';
        break;
      case ReceiverType.DEPARTMENT:
        result.show = true;
        result.selectListName = 'jhi-department-compact';
        result.props.labelField = 'name';
        result.optionProps.label = 'name';
        break;
      case ReceiverType.USER:
        result.show = true;
        result.selectListName = 'jhi-user-compact';
        result.props.labelField = 'firstName';
        result.optionProps.label = 'firstName';
        break;
      case ReceiverType.POSITION:
        result.show = true;
        result.selectListName = 'jhi-position-compact';
        result.props.labelField = 'name';
        result.optionProps.label = 'name';
        break;
      default:
        result.show = false;
        result.selectListName = '';
    }
    return result;
  }

  public retrieveAnnouncement(announcementId): void {
    if (!announcementId) {
      return;
    }
    this.announcementService()
      .find(announcementId)
      .then(res => {
        this.announcement = res;
        this.getFormData();
      });
  }

  public previousState(): void {
    this.$router.go(-1);
  }

  public initRelationships(): void {
    this.getData();
  }
  public getData() {
    if (this.announcementId || this.updateEntityId) {
      this.retrieveAnnouncement(this.announcementId || this.updateEntityId);
    } else {
      this.getFormData();
    }
  }
  public getFormData(formDataId?: number) {
    if (formDataId) {
      this.commonTableService()
        .find(formDataId)
        .then(res => {
          this.updateFormData(res);
        });
    } else {
      this.commonTableService()
        .findByEntityName('Announcement')
        .then(res => {
          this.updateFormData(res);
        });
    }
  }
  private updateFormData(res: any) {
    const commonTableData = res;
    if (commonTableData.formConfig && commonTableData.formConfig.length > 0) {
      this.formJsonData = JSON.parse(commonTableData.formConfig);
    } else {
      this.formJsonData.list = generateDataForDesigner(commonTableData);
    }
    if (this.formJsonData.list) {
      this.formJsonData.list.forEach(item => {
        if (item.type === 'modalSelect' && this.announcement[item.key]) {
          const isArray = Array.isArray(this.announcement[item.key]);
          const options = {};
          const propertyName = isArray ? 'id.in' : 'id.equals';
          // options[propertyName] = this.announcement[item.key];
          if (isArray) {
            if (this.relationshipsData[item.options.dynamicKey]) {
              if (this.announcement[item.key]) {
                const findIds = this.announcement[item.key].filter(idItem => {
                  return !this.relationshipsData[item.options.dynamicKey].some(dataItem => dataItem.id === idItem);
                });
                if (findIds.length > 0) {
                  options[propertyName] = findIds;
                }
              }
            }
          } else {
            if (this.announcement[item.key]) {
              if (!this.relationshipsData[item.options.dynamicKey].some(dataItem => dataItem.id === this.announcement[item.key])) {
                options[propertyName] = this.announcement[item.key];
              }
            }
          }
          if (options[propertyName]) {
            this[lowerFirst(item.commonTableName + 'Service')]
              .call(this)
              .retrieve(options)
              .then(res => {
                const newData = this.relationshipsData[item.options.dynamicKey].concat(res.data);
                delete this.relationshipsData[item.options.dynamicKey];
                this.$set(this.relationshipsData, item.options.dynamicKey, newData);
              });
          }
        }
      });
    }
    this.relationshipsData['entity'] = this.announcement;
    this.$nextTick(() => {
      this.updateForm.setData(getDataByFormField(this.formJsonData.list, this.announcement)); // loadsh的pick方法
    });
  }
}
